package univ.uchiha.esiag.gon.domaine.remote.impl;


import java.util.Vector;

import javax.rmi.PortableRemoteObject;

import org.omg.CORBA.ORB;
import org.omg.CORBA.Object;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;

import univ.uchiha.esiag.gon.broadcaster.BroadcasterRemote;
import univ.uchiha.esiag.gon.domaine.local.LocalDomaineManager;
import univ.uchiha.esiag.gon.domaine.remote.RemoteDomaineManager;

public class RemoteDomaineManagerImpl implements RemoteDomaineManager {
	private Vector<LocalDomaineManager> locals;
	private ORB orb;
	public RemoteDomaineManagerImpl(String[] args) {
		locals = new Vector<LocalDomaineManager>();
		orb = ORB.init(args, null);
		init();
	}
	public void init(){
		_RemoteDomaineManagerImpl_Tie tie = new _RemoteDomaineManagerImpl_Tie();
		tie.setTarget(this);
		try{
			POA root_POA = POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
			root_POA.the_POAManager().activate();
			Object objRef = root_POA.servant_to_reference(tie);
			String ior = orb.object_to_string(objRef);
			BroadcasterRemote broad = new BroadcasterRemote(ior);
			broad.start();
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
		new Thread(new Runnable() {
			
			public void run() {
				orb.run();
			}
		}).start();
	}
	public String[] getSubscriber(String topicName, String subscriber) {
		Vector<String> iors = new Vector<String>();
		for(int i = 0;i<locals.size();i++){
			try{
				String ior = locals.get(i).getSubscriber(topicName, subscriber);
				if(ior != null){
					iors.add(ior);
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		String[] iors1 = new String[iors.size()];
		for(int i = 0;i<iors1.length;i++){
			iors1[i] = iors.get(i);
		}
		return iors1;
	}
	public void register(String ior){
		Object objRef = orb.string_to_object(ior);
		LocalDomaineManager local = (LocalDomaineManager) PortableRemoteObject.narrow(objRef, LocalDomaineManager.class);
		try{
			locals.add(local);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		new RemoteDomaineManagerImpl(args);
	}
}
